/***************************singletondownloader.cpp**********************/
/*****************************************************************************/
/*******************Browsers Daily Build Updater************************/
/************Copyright (C) 2010-2011  Gianluigi Biancucci*************/
/*****************************************************************************/
/*****This is free software, and you are welcome to redistribute it****/
/*****and / or modify underthe terms of GPLV2 License.**************/
/*****This program comes with ABSOLUTELY NO WARRANTY*****/
/*****************************************************************************/

#include "singletondownloader.h"
#include <iostream>
#include <QVariant>
#include <QBuffer>
#include <QNetworkReply>
#include <QNetworkProxy>




SingletonDownloader::SingletonDownloader()
{

    proxy.setType(QNetworkProxy::HttpProxy);
    QObject::connect(this, SIGNAL(finished(QNetworkReply*)),this, SLOT(finished(QNetworkReply*)));
    progressTemp=0;
    progressUnit =0;
}

SingletonDownloader*  SingletonDownloader::_instance = 0;


SingletonDownloader* SingletonDownloader::getInstance()
{
    if (_instance == 0) {
        _instance = new SingletonDownloader;
    }
    return _instance;
}


bool SingletonDownloader::syncGet(QString url, QByteArray *BA){
    progressTemp=0;
    progressUnit=0;
    QNetworkReply* reply= this->get(QNetworkRequest(QUrl(url)));
    QObject::connect(reply, SIGNAL(downloadProgress( qint64,qint64)),this, SLOT(progress(qint64,qint64)));
    loop.exec();

    if(reply->error()==0){
        *BA = reply->readAll();
        delete reply;
        return true;
    } else {
        delete reply;
        return false;}

}



void SingletonDownloader::proxySet (QString pr, unsigned int po){
    proxy.setHostName(pr);
    proxy.setPort(po);
    this->setProxy(proxy);

}


void SingletonDownloader::proxyRemove (){

    this->setProxy(QNetworkProxy::NoProxy);

}



void SingletonDownloader::finished(QNetworkReply * reply){
    loop.exit();
    return;

}

void SingletonDownloader::progress ( qint64 bytesReceived, qint64 bytesTotal ) {
    progressUnit=bytesTotal/100;
    if(bytesReceived > (progressTemp+progressUnit)){
        qDebug("a");
        progressTemp=progressTemp+progressUnit;
        emit nextStep();
    }


}
